package gw.com.android.ui.news;

import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.gwtsz.gts2.hx.R;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.SharePopWindow;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.CommonUtils;
import www.com.library.view.BtnClickListener;
import www.com.library.view.RecyclerClickListener;

/**
 * 资讯详情
 * 
 * @author reeta
 * 
 */
public class NewsDetailActivity extends BaseActivity implements PlatformActionListener {

	@BindView(R.id.ll_content)
	View mContentLayout;
	@BindView(R.id.loading_progress_view)
	View mProgressView;
	@BindView(R.id.webview)
	WebView mWebView;
	@BindView(R.id.error_layout)
	View mErrorView;
	private DataItemDetail mItem;
	private String mTitle;
	private String mNewsUrl = "";
	private SharePopWindow mSharePopwindow;

	@Override
	protected int getLayoutView() {
		return R.layout.activity_news_detail;
	}

	@Override
	protected void initLayoutView() {
		mTitle = getIntent().getStringExtra("title");
		mItem = getIntent().getParcelableExtra("item");
		mTitleBar.setAppTitle(mTitle);
		//mTitleBar.setLeftResource(R.string.btn_back);

		//分享功能
		if(ConfigUtil.instance().hasShareFunction()){
			mTitleBar.setRightIcon(R.mipmap.a_nav_sharenews);
		}

		mTitleBar.setBtnClickListener(new BtnClickListener() {
			@Override
			public void onBtnClick(int viewID) {
				if(viewID == R.id.title_right_icon){
					if(null == mSharePopwindow){
						mSharePopwindow = new SharePopWindow(NewsDetailActivity.this, AppContances.SHARE_NEWS_TYPE, mTitleBar, mItem, new RecyclerClickListener() {
							@Override
							public void onClick(int position, DataItemDetail itemDetail) {
								mSharePopwindow.onShareFun(mSharePopwindow.getTitleId(position),
										mItem.getString("title"),mNewsUrl, mNewsUrl, NewsDetailActivity.this);
							}
						});
					}
					mSharePopwindow.show();
				}else{
                    finish();
				}
			}
		});
	}

	@Override
	protected void initViewData() {
		mProgressView.setVisibility(View.VISIBLE);
		mContentLayout.setVisibility(View.GONE);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setDefaultTextEncodingName("utf-8");
		mWebView.setBackgroundColor(0); // 设置背景色
		mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		mWebView.getSettings().setUseWideViewPort(true);
		mWebView.getSettings().setDomStorageEnabled(true);
		mWebView.getSettings().setLoadWithOverviewMode(true);
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
			WebView.setWebContentsDebuggingEnabled(true);
		}

		if (mWebView != null) {
			mWebView.setWebViewClient(new WebViewClient() {
				@Override
				public void onPageFinished(WebView view, String url) {
					cancelTask();
					mProgressView.setVisibility(View.GONE);
					mContentLayout.setVisibility(View.VISIBLE);
					mErrorView.setVisibility(View.GONE);
				}
			});
			mNewsUrl = ConfigUtil.instance().getNewsUrl(ConfigType.HTML_NEWS_DETIAL_TAG, mItem);
			Logger.e("资讯详情 mNewsUrl == " + mNewsUrl);
			initTimerTask();
			mWebView.loadUrl(mNewsUrl);
		}
	}

	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			try {
				switch (msg.what) {
					case AppContances.HANDLER_TIME_OUT:
						if(isResumed){
							showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012));
						}
						cancelTask();
						mProgressView.setVisibility(View.GONE);
						mContentLayout.setVisibility(View.GONE);
						mErrorView.setVisibility(View.VISIBLE);
						break;
				}
			} catch (Exception e) {
				Logger.e("加载网页异常！", e);
			}

		}
	};
	public Timer timer = new Timer();
	public TimerTask task;

	/**
	 * 初始化定时任务(处理提交订单超时)
	 */
	public void initTimerTask() {
		try {
			// 初始化定时器
			task = new TimerTask() {
				@Override
				public void run() {
					handler.sendEmptyMessage(AppContances.HANDLER_TIME_OUT);
				}
			};
			// 启动定时器,设定时间内如果没有响应,则提示超时信息
			timer.schedule(task, AppContances.WEBVIEW_TIME_OUT);
		} catch (Exception e) {
			Logger.e("初始化定时任务异常！", e);
		}
	}

	/**
	 * 取消超时定时
	 */
	public void cancelTask(){
		if (null != task) {
			task.cancel();
			task = null;
		}
	}

	@OnClick(R.id.error_layout)
	public void errorClick(){
		if(CommonUtils.isFastDoubleClick()){
			return;
		}
		if(null != mErrorView){
			mErrorView.setVisibility(View.GONE);
		}
		if(null != mProgressView){
			mProgressView.setVisibility(View.VISIBLE);
		}
		if(null != mWebView){
			initTimerTask();
			mWebView.loadUrl(mNewsUrl);
		}
	}

	private Handler mShareHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case AppContances.HANDLER_SHARE_SUCCESS:
					showToastPopWindow(AppMain.getAppString(R.string.app_share_success));
					break;
				case AppContances.HANDLER_SHARE_CANCEL:
					showToastPopWindow(AppMain.getAppString(R.string.app_share_cancel));
					break;
				case AppContances.HANDLER_SHARE_FAIL:
					showToastPopWindow(AppMain.getAppString(R.string.app_share_fail) + msg.obj);
					break;
				default:
					break;
			}
		}

	};

	@Override
	public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
		mShareHandler.sendEmptyMessage(AppContances.HANDLER_SHARE_SUCCESS);
	}

	@Override
	public void onError(Platform platform, int i, Throwable throwable) {
		throwable.printStackTrace();
		Message msg = new Message();
		msg.what = AppContances.HANDLER_SHARE_FAIL;
		msg.obj = throwable.getMessage();
		mShareHandler.sendMessage(msg);
	}

	@Override
	public void onCancel(Platform platform, int i) {
		mShareHandler.sendEmptyMessage(AppContances.HANDLER_SHARE_CANCEL);
	}

	@Override
	public void finish() {
		super.finish();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(null != mShareHandler){
			mShareHandler.removeCallbacksAndMessages(null);
			mShareHandler = null;
		}
		cancelTask();
		if (null != timer) {
			timer.cancel();
			timer = null;
		}
		/*if (null != mWebView) {
			mWebView.setVisibility(View.GONE);
			mWebView.destroy();
			mWebView = null;
		}*/
	}
  /** 先执行onDetachedFromWindow()，后执行WebView.destroy()解决webview内存泄露的问题 **/
	@Override public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		destroy();
	}
	public void destroy() {
		if (mWebView != null) {
			// 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
			// destory()
			ViewParent parent = mWebView.getParent();
			if (parent != null) {
				((ViewGroup) parent).removeView(mWebView);
			}

			mWebView.stopLoading();
			// 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
			mWebView.getSettings().setJavaScriptEnabled(false);
			mWebView.clearHistory();
			mWebView.clearView();
			mWebView.removeAllViews();

			try {
				mWebView.destroy();
			} catch (Throwable ex) {

			}
		}
	}
}
